import Utils from "./utils";

export interface LibraryRecord {
    key: string;
};

export class Library<T extends LibraryRecord> {
    private __inited = false;
    protected _group = "";
    protected _configMap: Map<string, T> = new Map();

    constructor(group: string) {
        this._group = group;
    }

    init() {
        let jsons = Utils.loader.getAssets<cc.JsonAsset>("", this._group, "cc.JsonAsset");
        jsons.forEach(ja => {
            if (typeof ja.json === "object" && ja.json instanceof Array) {
                ja.json.forEach((conf: T) => {
                    this._configMap.set(conf.key, conf);
                });
            }
            else {
                let conf: T = ja.json;
                this._configMap.set(conf.key, conf);
            }
        });
        this.__inited = true;
    }
    setConfig(key: string, val: T) {
        if (!this.__inited) {
            this.init();
        }
        this._configMap.set(key, val);
    }
    getConfig(key: string): T {
        if (!this.__inited) {
            this.init();
        }
        return this._configMap.get(key) || null;
    }
    getAllConfigs() {
        if (!this.__inited) {
            this.init();
        }
        return Array.from(this._configMap);
    }
};